package com.example.prison.util;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.prison.config.SocketResponse;
import com.example.prison.entity.AreaManagement;
import com.example.prison.entity.DeviceInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

import static com.example.prison.protocol.StringUtil.*;

@Slf4j
public class APIUtil {

    /**
     * 设置防区错误信息
     * @return 实时电压值、实时电流值、线型电压设为--
     */
    public static AreaManagement setErrorArea(AreaManagement area) {
        area.setVoltageA("--");
        area.setCurrentA("--");
        area.setStatusA("6");
        area.setVoltageB("--");
        area.setCurrentB("--");
        area.setStatusB("6");
        area.setVoltageC("--");
        area.setCurrentC("--");
        area.setStatusC("6");
        area.setLinearVoltageAB("--");
        area.setLinearVoltageAC("--");
        area.setLinearVoltageBC("--");
        area.setHighRatedVoltage("--");
        area.setRatedVoltage("--");
        area.setRatedCurrent("--");
        return area;
    }

    /**
     * 设置防区关闭信息
     * @return 实时电压值、实时电流值、线型电压设为0
     */
    public static AreaManagement setCloseArea(AreaManagement area) {
        area.setVoltageA("0");
        area.setCurrentA("0");
        area.setStatusA("3");
        area.setVoltageB("0");
        area.setCurrentB("0");
        area.setStatusB("3");
        area.setVoltageC("0");
        area.setCurrentC("0");
        area.setStatusC("3");
        area.setLinearVoltageAB("0");
        area.setLinearVoltageAC("0");
        area.setLinearVoltageBC("0");
        area.setHighRatedVoltage("0");
        area.setLinearVoltage("0");
        area.setRatedVoltage("0");
        area.setRatedCurrent("0");
        area.setAlarmStatus("防区关闭");
        area.setAlarmLevel("防区关闭");
        area.setDetection(0);
        return area;
    }

    /**
     * 将当前时间减去time秒并返回
     * @return
     */
    public static long timeSubtraction (String time1, String time2) {
        long res = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1;
        Date date2;
        try {
            date1 = format.parse(time1);
            date2 = format.parse(time2);

            long diff = date1.getTime() - date2.getTime();
            long seconds = diff / 1000;

            res = seconds;
//            System.out.println(time1+" " +time2+"时间相差：" + seconds + "秒");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 计算电压百分比
     */
    public static String Countresult(String voltage, String ratedVoltage) {
        String percentage = "";
        int v = Integer.parseInt(voltage);
        int rateV = Integer.parseInt(ratedVoltage);
        Integer result  = (rateV - v)*100/(rateV*100);
        percentage = String.valueOf(result);
        return percentage;
    }

    /**
     * 计算电压警戒等级
     */
    public static String CountAlarmLevel(String voltage, String oldVoltage, String alarmOne, String alarmTwo, String alarmThree){
        double v = Double.parseDouble(voltage);
        double oldV = Double.parseDouble(oldVoltage);
        double vo = oldV - v;
        double result  = vo*100/oldV;

        String alarmLevel = "";
        if(result >= Double.parseDouble(alarmOne) ) {
            alarmLevel = "一级";
        } else if(result < Double.parseDouble(alarmOne) && result >= Double.parseDouble(alarmTwo)) {
            alarmLevel = "二级";
        } else if(result < Double.parseDouble(alarmTwo) && result >= Double.parseDouble(alarmThree)) {
            alarmLevel = "三级";
        } else if(result < Double.parseDouble(alarmThree)){
            alarmLevel = "正常";
//            alarmLevel = "1";
        }
        System.out.println("实时电压："+voltage+"，旧电压"+oldVoltage+", 百分比："+alarmOne+"/"+alarmTwo+"/"+alarmThree+", 电压警戒等级:"+alarmLevel);
        return alarmLevel;
    }
    /**
     * 返回状态对应报警
     */
    public static String getAlarmStatus(String alarmStatus){
        String alarmLevel = "";
        if(alarmStatus == "1" ) {
            alarmLevel = "正常";
        } else if(alarmStatus == "2") {
            alarmLevel = "断网";
        } else if(alarmStatus == "3") {
            alarmLevel = "断电";
        } else if(alarmStatus == "4"){
            alarmLevel = "触网";
        } else if(alarmStatus == "5"){
            alarmLevel = "短网";
        }
        return alarmLevel;
    }
    /**
     * 将当前时间减去hour小时并返回
     */
    public static String hourProcess(Integer hour) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.add(Calendar.HOUR,hour);
        Date dt1 = rightNow.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(dt1);
    }

    /**
     * 判断字符串是否为整数
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * int转byte[1]
     */
    public static byte[] intToBytes(int a){
        byte[] ans=new byte[1];
        for(int i=0;i<1;i++)
            ans[i]=(byte)(a>>(i*8));//截断 int 的低 8 位为一个字节 byte，并存储起来
        return ans;
    }

    /**
     * int转2个字节的byte[]
     */
    public static byte[] intToTwoBytes(int value) {
        byte[] result = new byte[2];
        result[0] = (byte) ((value >> 8) & 0xFF); // 高8位
        result[1] = (byte) (value & 0xFF);        // 低8位
        return result;
    }

    /**
     * 将一个整数转换为一个4字节的字节数组
     * @param number
     * @return
     */
    public static byte[] intToBytes(int number, int byteNum) {
        return ByteBuffer.allocate(4).putInt(number).array();
    }



    /**
     * 连接byte[]数组
     */
    public static byte[] combineArrays(byte[]... a) {
        int massLength = 0;
        for (byte[] b : a) {
            massLength += b.length;
        }
        byte[] c = new byte[massLength];
        byte[] d;
        int index = 0;
        for (byte[] anA : a) {
            d = anA;
            System.arraycopy(d, 0, c, 0 + index, d.length);
            index += d.length;
        }
        return c;
    }


    /**
     * 查询实时状态-直接接收数据打印
     */
    public static SocketResponse<?> getBaseSocketResponse(String ip, Integer port, Integer moduleAddress, byte[] message) {
        int flag = 0;
        Socket socket = null;
        try {
            log.info("准备建立socket连接");
            socket = new Socket(ip,port);
            OutputStream outputStream = socket.getOutputStream();
            socket.setSoTimeout(2000);
            log.info("socket连接建立成功！IP："+ip+", port："+port);
            byte[] sendMessage = APIUtil.combineArrays(APIUtil.intToBytes(moduleAddress), message);//查询命令(未加CRC)
            byte[] CRC8 = APIUtil.intToBytes(Crc8Util.CRC8(sendMessage, 0 , sendMessage.length));//计算CRC
            //查询设备状态
            byte[] sendInfo = APIUtil.combineArrays(sendMessage, CRC8);
            outputStream.write(sendInfo);
            outputStream.flush();
            log.info("查询设备状态=====>" + byteToPrintAsciiHexString(sendInfo));
            if(ObjectUtils.isEmpty(socket.getInputStream())) {
                log.info("查询设备状态命令发送内容为空："+socket.getInputStream());
                return SocketResponse.error("查询命令发送内容为空", socket.getInputStream());
            }
            flag = 1;
            InputStream inputStream = socket.getInputStream();
            Integer bsSize = 0;
            if (message[message.length - 1] == 0x08 && message[0] == 0x03) {
                bsSize = 20; //查询小板电压状态
            } else if (message[message.length - 1] == 0x10 && message[0] == 0x03){
                bsSize = 48; //查询大板电压状态
            } else if (message[message.length - 1] == 0x01 && message[0] == 0x03){
                bsSize = 6; //查询板子类型
            } else if (message[0] == 0x10){
                bsSize = 4; //查询板子类型
            }
            byte[] bs = new byte[bsSize];
            inputStream.read(bs);
            String res1 = bytesTo16HexString(bs);
            if(ObjectUtils.isEmpty(bs)) {
                log.info("查询设备状态命令已发送，服务端响应为空："+ Arrays.toString(bs));
                return SocketResponse.error("设备响应为空", bs);
            }
            log.info("服务端响应====>["+res1+"]");

            //释放资源
            socket.shutdownOutput();
            inputStream.close();
            outputStream.close();
            socket.close();

            return SocketResponse.success(res1, flag, bs);
        } catch (IOException e) {
            if(flag == 1) {
                log.error("连接超时,该模块地址无数据返回");
                return SocketResponse.error("连接超时,无数据返回");
            } else {
                log.error("socket连接建立失败！IP："+ip+", port："+port);
                log.error("设备连接失败");
                return SocketResponse.error("设备连接失败");
            }
        }
        finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 查询大板电压实时状态-并塞入防区对应数值
     */
    public static AreaManagement getLagerAreaStatusMessage(AreaManagement area, String ip, Integer port, Integer moduleAddress, byte[] message) {
//        message = new byte[]{0x03, 0x00, 0x01, 0x00, 0x10};
        SocketResponse<?> response = getBaseSocketResponse(ip, port, moduleAddress, message);
        if(response.getStatus() != "success") {
            setErrorArea(area);
            area.setAlarmLevel(response.getMessage());
            area.setAlarmStatus(response.getMessage());
            return area;
        }

        String res1 = response.getMessage();
        byte[] bs = (byte[]) response.getData();
        log.info("设备返回的byte数组："+ Arrays.toString(bs));

        String hexStr = "";
        if (message[message.length - 1] == 0x08 && message[0] == 0x03) {
            hexStr = statusSmallResponseHexStringParse(res1); //查询小板电压状态
        } else if (message[message.length - 1] == 0x10 && message[0] == 0x03) {
            hexStr = statusLargeResponseHexStringParse(res1); //查询大板电压状态
        } else if (message[message.length - 1] == 0x01 && message[0] == 0x03) {
            hexStr = typeResponseHexStringParse(res1); //查询板子类型
        } else if(message[0] == 0x10) {
            hexStr = setResponseHexStringParse(res1); //检查设置
        }
        log.info("服务端响应====>[" + res1 + "],数据解析：{" + hexStr + "}");
        //分解响应信息
        String[] a = new String[50];
        if (message[message.length - 1] == 0x08 && message[0] == 0x03) {
            a = APIUtil.decodeSmallStatus(res1);
        } else if (message[message.length - 1] == 0x10 && message[0] == 0x03){
            a = APIUtil.decodeLargeStatus(res1);
        } else if (message[message.length - 1] == 0x01 && message[0] == 0x03){
            a = APIUtil.decodeType(res1);
        } else if(message[0] == 0x10) {
            a = APIUtil.decodeSet(res1); //检查设置
        }
        a = Arrays.stream(a)
                .filter(s -> s != null)
                .toArray(String[]::new);
        log.info(Arrays.toString(a));

        if (!a[1].equals("3")) {
            log.info("设备接收数据失败" + res1);
            setErrorArea(area);
            area.setAlarmLevel("设备接收数据失败");
            area.setAlarmStatus("设备接收数据失败");
            return area;
        }
        //计算校验crc
        byte[] bsOutCrc = new byte[bs.length - 1];
        System.arraycopy(bs, 0, bsOutCrc, 0, bsOutCrc.length);
        int crc8 = Crc8Util.CRC8(bsOutCrc, 0, bsOutCrc.length);
        if (Integer.parseInt(a[a.length - 1]) != crc8) {
            log.info("crc计算数据："+Arrays.toString(bsOutCrc)+", 计算结果："+crc8+"="+Integer.toHexString(crc8));
            log.info("服务端响应数据CRC校验结果错误" + res1 + ",发送crc:" + crc8 + ",接收crc:" + a[a.length - 1]);
            setErrorArea(area);
            area.setAlarmLevel("设备响应数据CRC校验失败");
            area.setAlarmStatus("设备响应数据CRC校验失败");
            return area;
        }

        //塞入大板实时电压值
        area = setLargeAreaStatus(a,area);
        log.info(String.valueOf(area));
        return area;
    }

    /**
     * 查询实时状态-直接接收数据打印
     */
    public static String getStatusMessage(String ip, Integer port, Integer moduleAddress, byte[] message) {

        SocketResponse<?> response = getBaseSocketResponse(ip, port, moduleAddress, message);
        if(response.getStatus() != "success") {
            return response.getMessage();
        }
        String res1 = response.getMessage();
        byte[] bs = (byte[]) response.getData();
        log.info("设备返回的byte数组：" + Arrays.toString(bs));


        String hexStr = "";
        if (message[message.length - 1] == 0x08 && message[0] == 0x03) {
            hexStr = statusSmallResponseHexStringParse(res1); //查询小板电压状态
        } else if (message[message.length - 1] == 0x10 && message[0] == 0x03) {
            hexStr = statusLargeResponseHexStringParse(res1); //查询大板电压状态
        } else if (message[message.length - 1] == 0x01 && message[0] == 0x03) {
            hexStr = typeResponseHexStringParse(res1); //查询板子类型
        } else if(message[0] == 0x10) {
            hexStr = setResponseHexStringParse(res1); //检查设置
        }
        log.info("服务端响应====>[" + res1 + "],数据解析：{" + hexStr + "}");
        //分解响应信息
        String[] a = new String[50];
        if (message[message.length - 1] == 0x08 && message[0] == 0x03) {
            a = APIUtil.decodeSmallStatus(res1);
        } else if (message[message.length - 1] == 0x10 && message[0] == 0x03){
            a = APIUtil.decodeLargeStatus(res1);
        } else if (message[message.length - 1] == 0x01 && message[0] == 0x03){
            a = APIUtil.decodeType(res1);
        } else if(message[0] == 0x10) {
            a = APIUtil.decodeSet(res1); //检查设置
        }
        a = Arrays.stream(a)
                .filter(s -> s != null)
                .toArray(String[]::new);
        log.info(Arrays.toString(a));

        if (a[1].equals("83")) {
            log.info("服务端响应数据非对应响应接收失败" + res1);
            return "服务端响应数据非对应响应接收失败" + res1;
        }
        //计算校验crc
        byte[] bsOutCrc = new byte[bs.length - 1];
        System.arraycopy(bs, 0, bsOutCrc, 0, bsOutCrc.length);
        int crc8 = Crc8Util.CRC8(bsOutCrc, 0, bsOutCrc.length);
        if (Integer.parseInt(a[a.length - 1]) != crc8) {
            log.info("crc计算数据：" + Arrays.toString(bsOutCrc) + ", 计算结果：" + crc8 + "=" + Integer.toHexString(crc8));
            log.info("服务端响应数据CRC校验结果错误" + res1 + ",发送crc:" + crc8 + ",接收crc:" + a[a.length - 1]);
            return "服务端响应数据CRC校验结果错误" + res1 + ",发送crc:" + crc8 + ",接收crc:" + a[a.length - 1];
        }
        return res1;

    }

    /**
     * 检测设置-直接接收数据打印
     */
    public static String setDetectionSettings(String ip, Integer port, Integer moduleAddress, byte[] message) {
        SocketResponse<?> response = getBaseSocketResponse(ip, port, moduleAddress, message);
        if(response.getStatus() != "success") {
            return response.getMessage();
        }
        String res1 = response.getMessage();
        return res1;
    }


    /**
     * 存储查询状态数值-直接接收数据打印
     */
    public static String getStatusLog(String ip, Integer port) {
        int flag = 0;
        String message = "准备socket连接\n";
        byte[] result = {0};

        // 创建一个字符串变量，用于存储读取到的数据
        String data = null;
        Socket socket = null;
        try {
//            //Socket socket = new Socket("127.0.0.1", 8888);//192.168.3.140   10.10.10.110
            socket = new Socket(ip,port);
            socket.setSoTimeout(2000);
            message = "";
            result = new byte[]{1};

            flag = 1;
            String res1 = "";
            InputStream inputStream = socket.getInputStream();
//            byte[] bs = new byte[10000];
//            inputStream.read(bs);
//            message = AsciiToString(bs);

//            String hexStr = statusSmallResponseHexStringParse(res1);

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            // 循环读取数据，直到读取到末尾
            while ((data = bufferedReader.readLine()) != null) {
                // 在这里处理读取到的数据，可以打印、解析等操作
                message = message + data;
                System.out.println("开始data:"+data+"结尾");
            }

//            if(ObjectUtils.isEmpty(data)) {
//                data = "无数据可读取";
//            }

            // 关闭输入流
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();


            log.info("服务端响应====>"+message+"");
            //释放资源
            inputStream.close();
//            socket.shutdownOutput();
            socket.close();

            return message;
        } catch (IOException e) {
            System.out.println(message);
            if(flag == 1) {
                return message;
            } else {
                return message + "连接socket失败";
            }
        }
        finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 存储查询类型数值
     */
    public static DeviceInfo getType(DeviceInfo device) {
        Integer moduleAddress = device.getModuleAddress();
        int flag = 0;
        Socket socket = null;
        try {
            socket = new Socket(device.getIp(),device.getPort());
            socket.setSoTimeout(2000);
            OutputStream outputStream = socket.getOutputStream();
            byte[] message = new byte[]{0x03, 0x00, 0x03, 0x00, 0x01};
            byte[] sendMessage = new byte[6];
            sendMessage = APIUtil.combineArrays(APIUtil.intToBytes(moduleAddress), message);//查询设备类型
//            byte[] crc = Crc16Util.getCrc16(sendMessage);
////        log.info("crc校验"+ Arrays.toString(crc));
//            byte[] crc16 = new byte[1];
//            System.arraycopy(crc, 0, crc16, 0, 1);
            byte[] CRC8 = APIUtil.intToBytes(Crc8Util.CRC8(sendMessage, 0 , sendMessage.length));
            byte[] sendInfo = APIUtil.combineArrays(sendMessage, CRC8);
            outputStream.write(sendInfo);
            outputStream.flush();
            log.info("查询设备类型=====>" + byteToPrintAsciiHexString(sendInfo));
            if(ObjectUtils.isEmpty(socket.getInputStream())) {
                device.setType("服务端无响应");
                log.info("查询设备类型命令已发送，服务端无响应");
                return device;
            }

            flag = 1;

            InputStream inputStream = socket.getInputStream();
            byte[] bs = new byte[6];
            inputStream.read(bs);
            String res1 = bytesTo16HexString(bs);
            String hexStr = typeResponseHexStringParse(res1);
            log.info("服务端响应====>["+res1+"],数据解析：{"+hexStr+"}");
            String[] a = APIUtil.decodeType(res1);
            //释放资源
            socket.shutdownOutput();
            inputStream.close();
            outputStream.close();
            socket.close();

            if(!a[1].equals("3")) {
                log.info("服务端响应数据非对应响应");
                return device;
            }
            //校验crc
            byte[] bsOutCrc = new byte[5];
            System.arraycopy(bs,0,bsOutCrc,0,bsOutCrc.length);
            int crc8 = Crc8Util.CRC8(bsOutCrc, 0 , bsOutCrc.length);
            if(Integer.parseInt(a[4]) != crc8) {
                device.setType("CRC校验结果错误");
                log.info("CRC校验结果错误"+res1);
                return device;
            }

            if (a[1].equals("131")) {
                log.info("0183数据接收失败"+res1);
                device.setType("0183数据接收失败");
            }
            if (Integer.parseInt(a[3]) == 1) {
                device.setType("类型1");
            } else {
                device.setType("类型2");
            }
            return device;
        } catch (IOException e) {
            if(flag == 1) {
                device.setType("无数据返回");
                log.info("连接超时,该模块地址无数据返回");
                return device;
            } else {
                device.setType("设备无响应");
                log.info("设备无响应，连接失败");
                return device;
            }
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String[] deleteArrayNull(String string[]) {
        String strArr[] = string;

        // step1: 定义一个list列表，并循环赋值
        ArrayList<String> strList = new ArrayList<String>();
        for (int i = 0; i < strArr.length; i++) {
            strList.add(strArr[i]);
        }

        // step2: 删除list列表中所有的空值
        while (strList.remove(null));
        while (strList.remove(""));

        // step3: 把list列表转换给一个新定义的中间数组，并赋值给它
        String strArrLast[] = strList.toArray(new String[strList.size()]);

        return strArrLast;
    }

    public static String typeResponseParse(DeviceInfo device) {
        String str = "设备名称:"+device.getDeviceName()+",设备编号:"+device.getDeviceNumber() +",设备类型:"+device.getType()+",模块地址:"+device.getModuleAddress();
        return str;
    }

    /**
     * 状态信息分解（小板设备）
     * @param hexString
     * @return
     */
    public static String statusSmallResponseHexStringParse(String hexString) {
        String[] a = APIUtil.decodeSmallStatus(hexString);
        String str = "设备地址:"+a[0]+",功能码:"+a[1] +",数量:"+a[2]+",电压1状态:"+a[3]+",电压2状态:"+a[4] +",电压1电压值:"+a[5]+",电压2电压值:"+a[6]+",电池1电压值："+a[7]
                +",电池1温度值："+a[8]+",空气传感器1温度值："+a[9]+",输入电压值"+a[10]+",CRC："+a[11];
        return str;
    }

    /*** 解析状态接收信息(小板)*/
    public static String[] decodeSmallStatus(String str) {
        String[] decodeStr = new String[str.length()];
        decodeStr[0] = String.valueOf(Integer.parseInt(str.substring(0,2),16));//设备地址
        decodeStr[1] = String.valueOf(Integer.parseInt(str.substring(2,4),16));//功能码
        decodeStr[2] = String.valueOf(Integer.parseInt(str.substring(4,6),16));//数量
        decodeStr[3] = String.valueOf(Integer.parseInt(str.substring(6,10),16));//数值1 电压1 状态
        decodeStr[4] = String.valueOf(Integer.parseInt(str.substring(10,14),16));//数值2 电压2 状态
        decodeStr[5] = String.valueOf(Integer.parseInt(str.substring(14,18),16));//数值3 电压1 电压值
        decodeStr[6] = String.valueOf(Integer.parseInt(str.substring(18,22),16));//数值4 电压2 电压值
        decodeStr[7] = String.valueOf(Integer.parseInt(str.substring(22,26),16));//数值5 电池1 电压值
        decodeStr[8] = String.valueOf(Integer.parseInt(str.substring(26,30),16));//数值6 电池1 温度值
        decodeStr[9] = String.valueOf(Integer.parseInt(str.substring(30,34),16));//数值7 空气传感器1 温度值
        decodeStr[10] = String.valueOf(Integer.parseInt(str.substring(34,38),16));//数值8 输入电压值
        decodeStr[11] = String.valueOf(Integer.parseInt(str.substring(38,40),16));//CRC
        decodeStr = deleteArrayNull(decodeStr);
        return decodeStr;
    }

//    /**
//     * 设置防区电压状态信息（小板设备）
//     */
//    public static AreaManagement setSmallAreaStatus(String[] decodeStr, AreaManagement area) {
//        area.setStatus1(decodeStr[3]);
//        area.setStatus2(decodeStr[4]);
//        area.setVoltage1(decodeStr[5]);
//        area.setVoltage2(decodeStr[6]);
//        area.setBatteryVoltage(decodeStr[7]);
//        area.setBatteryT(decodeStr[8]);
//        area.setAir(decodeStr[9]);
//        area.setInVoltage(decodeStr[10]);
//        return area;
//    }

    /**
     * 电压状态信息分解（大板设备）
     * @param hexString
     * @return
     */
    public static String statusLargeResponseHexStringParse(String hexString) {
        String[] a = APIUtil.decodeLargeStatus(hexString);
        String str = "设备地址:"+a[0]+",功能码:"+a[1] +",数量:"+a[2]
                +",高压A实时电压值UHA:"+a[3]+",高压A实时电流值IHA:"+a[4] +",高压A状态:"+a[5]
                +",高压B实时电压值UHB:"+a[6]+",高压B实时电流值IHB:"+a[7] +",高压B状态:"+a[8]
                +",高压C实时电压值UHC:"+a[9]+",高压C实时电流值IHC:"+a[10] +",高压C状态:"+a[11]
                +",220V A电压值:"+a[12]+",220V A电流值:"+a[13] +",220V B电压值:"+a[14]+",220V B电流值:"+a[15]
                +",220V C电压值:"+a[16]+",220V C电流值:"+a[17]
                +",AB间线性电压:"+a[18]+",BC间线性电压:"+a[19] +",AC间线性电压:"+a[20] +",输入电源额定电压UABC:"+a[21]
                +",电池 电压值:"+a[22] +",电池 温度值:"+a[23] +",空气 温度值"+a[24] +",CRC"+a[25];
        return str;
    }

    /**
     * 解析状态接收信息(大板)
     */
    public static String[] decodeLargeStatus(String str) {
        String[] decodeStr = new String[str.length()];
        decodeStr[0] = String.valueOf(Integer.parseInt(str.substring(0,2),16));//设备地址
        decodeStr[1] = String.valueOf(Integer.parseInt(str.substring(2,4),16));//功能码
        decodeStr[2] = String.valueOf(Integer.parseInt(str.substring(4,6),16));//数量
        decodeStr[3] = String.valueOf(Integer.parseInt(str.substring(6,10),16));// 高压A实时电压值UHA
        decodeStr[4] = String.valueOf(Integer.parseInt(str.substring(10,14),16));// 高压A实时电流值IHA
        decodeStr[5] = String.valueOf(Integer.parseInt(str.substring(14,18),16));// 高压A状态
        decodeStr[6] = String.valueOf(Integer.parseInt(str.substring(18,22),16));// 高压B实时电压值UHB
        decodeStr[7] = String.valueOf(Integer.parseInt(str.substring(22,26),16));// 高压B实时电流值IHB
        decodeStr[8] = String.valueOf(Integer.parseInt(str.substring(26,30),16));// 高压B状态
        decodeStr[9] = String.valueOf(Integer.parseInt(str.substring(30,34),16));// 高压C实时电压值UHC
        decodeStr[10] = String.valueOf(Integer.parseInt(str.substring(34,38),16));//高压C实时电流值IHC
        decodeStr[11] = String.valueOf(Integer.parseInt(str.substring(38,42),16));//高压C状态
        decodeStr[12] = String.valueOf(Integer.parseInt(str.substring(42,46),16));//A电压值
        decodeStr[13] = String.valueOf(hexToFloat(str.substring(46,50)));//A电流值 float
        decodeStr[14] = String.valueOf(Integer.parseInt(str.substring(50,54),16));//B电压值
        decodeStr[15] = String.valueOf(hexToFloat(str.substring(54,58)));//B电流值 float
        decodeStr[16] = String.valueOf(Integer.parseInt(str.substring(58,62),16));//C电压值
        decodeStr[17] = String.valueOf(hexToFloat(str.substring(62,66)));//C电流值 float
        decodeStr[18] = String.valueOf(Integer.parseInt(str.substring(66,70),16));//AB间线性电压
        decodeStr[19] = String.valueOf(Integer.parseInt(str.substring(70,74),16));//BC间线性电压
        decodeStr[20] = String.valueOf(Integer.parseInt(str.substring(74,78),16));//AC间线性电压
        decodeStr[21] = String.valueOf(hexToFloat(str.substring(78,82)));//输入电源额定电压UABC float
        decodeStr[22] = String.valueOf(hexToFloat(str.substring(82,86)));//电池电压值 float
        decodeStr[23] = String.valueOf(Integer.parseInt(str.substring(86,90),16));//电池温度值
        decodeStr[24] = String.valueOf(Integer.parseInt(str.substring(90,94),16));//空气温度值
        decodeStr[25] = String.valueOf(Integer.parseInt(str.substring(94,96),16));//CRC
        decodeStr = deleteArrayNull(decodeStr);
        return decodeStr;
    }

    /**
     * 设置防区电压状态信息（大板设备）
     */
    public static AreaManagement setLargeAreaStatus(String[] decodeStr, AreaManagement area) {
        area.setVoltageA(decodeStr[3]);
        area.setCurrentA(decodeStr[4]);
        area.setStatusA(decodeStr[5]);
        area.setVoltageB(decodeStr[6]);
        area.setCurrentB(decodeStr[7]);
        area.setStatusB(decodeStr[8]);
        area.setVoltageC(decodeStr[9]);
        area.setCurrentC(decodeStr[10]);
        area.setStatusC(decodeStr[11]);
        area.setLinearVoltageAB(decodeStr[18]);
        area.setLinearVoltageBC(decodeStr[19]);
        area.setLinearVoltageAC(decodeStr[20]);
        area.setRatedVoltage(decodeStr[21]);
        return area;
    }


    /**
     * 板子类型信息分解
     * @param hexString
     * @return
     */
    public static String typeResponseHexStringParse(String hexString) {
        String[] a = APIUtil.decodeType(hexString);
        String str = "设备地址:"+a[0]+",功能码:"+a[1] +",数量:"+a[2]+",类型:"+a[3]+",CRC："+a[4];
        return str;
    }

    /**
     * 解析状态接收信息
     */
    public static String[] decodeType(String str) {
        String[] decodeStr = new String[15];
        decodeStr[0] = String.valueOf(Integer.parseInt(str.substring(0,2),16));//设备地址
        decodeStr[1] = String.valueOf(Integer.parseInt(str.substring(2,4),16));//功能码
        decodeStr[2] = String.valueOf(Integer.parseInt(str.substring(4,6),16));//数量
        decodeStr[3] = String.valueOf(Integer.parseInt(str.substring(6,10),16));//数值
        decodeStr[4] = String.valueOf(Integer.parseInt(str.substring(10,12),16));//CRC
        decodeStr = deleteArrayNull(decodeStr);
        return decodeStr;
    }

    /**
     * 板子检测设置信息分解
     * @param hexString
     * @return
     */
    public static String setResponseHexStringParse(String hexString) {
        String[] a = APIUtil.decodeSet(hexString);
        String str = "设备地址:"+a[0]+",功能码:"+a[1] +",数值(成功/失败):"+a[2]+", CRC:"+a[3];
        return str;
    }
    /**
     * 解析检测设置接收信息
     */
    public static String[] decodeSet(String str) {
        String[] decodeStr = new String[15];
        decodeStr[0] = String.valueOf(Integer.parseInt(str.substring(0,2),16));//设备地址
        decodeStr[1] = String.valueOf(Integer.parseInt(str.substring(2,4),16));//功能码
        decodeStr[2] = String.valueOf(Integer.parseInt(str.substring(4,6),16));//数值
        decodeStr[3] = String.valueOf(Integer.parseInt(str.substring(6,8),16));//CRC
        decodeStr = deleteArrayNull(decodeStr);
        return decodeStr;
    }

    /**
     * 将16进制字符串转换为float类型
     * @param hex
     * @return
     */
    public static float hexToFloat(String hex) {
        // 将16进制字符串转换为short类型的整数
        short intValue = (short) Integer.parseInt(hex, 16);
        // 将short类型的整数转换为float类型
        float floatValue = (float) intValue;
        return floatValue;
    }

}
